package com.hk.Mgr.web.controller;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.kyc.CardReq;
import com.hk.Mgr.web.message.kyc.CardRes;
import com.hk.Mgr.web.message.kyc.UserCardReq;
import com.hk.Mgr.web.message.kyc.UserCardRes;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.ConstantCard;
import com.hk.commons.DateUtil;
import com.hk.commons.HqlFilter;
import com.hk.commons.ReqToModelHelper;
import com.hk.commons.StringHelper;
import com.hk.commons.enm.CardsTypeEnum;
import com.hk.commons.enm.UserCardsStatusEnum;
import com.hk.commons.entity.Card;
import com.hk.commons.entity.Parameter;
import com.hk.commons.entity.Points;
import com.hk.commons.entity.UserCard;
import com.hk.commons.entity.UserExtraInfo;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.utils.sys.DateHelper;
import com.hk.commons.vo.app.CheckResultMsg;
import com.hk.service.IPointsFunction;
import com.hk.service.IUserExtraInfo;
import com.hk.service.kyc.ICard;
import com.hk.service.kyc.IPoints;
import com.hk.service.kyc.IUserCard;
import com.hk.service.order.IParameter;
import com.hk.service.sys.ISysUser;

/**
 * 用户积分
 * 
 * @author jeff
 *
 */
@Controller
@RequestMapping(value = BaseCtrl.MgrRootPath + "/userCardCtr")
public class UserCardCtrl extends BaseCtrl {

	private Logger logger = LoggerFactory.getLogger(UserCardCtrl.class);

	@Autowired
	private ISysUser userService;

	@Autowired
	private ICard cardService;

	@Autowired
	private IUserCard userCardService;

	@Autowired
	private IParameter parmService;

	/**
	 * 获取加息券
	 * 
	 * @param userId
	 *            用户id, cardId 加息券id
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<List<UserCardRes>> list(@RequestBody UserCardReq req) {
		ResponseBase<List<UserCardRes>> resp = new ResponseBase<List<UserCardRes>>();
		List<UserCardRes> cardResList = new ArrayList<UserCardRes>();

		String userName = req.getUserName();
		Integer cardType = req.getCardType();

		Integer status = req.getStatus();

		HqlFilter hqlFilter = new HqlFilter();

		logger.info("mgr/userCardCtr/list userName = " + userName
				+ "  cardType = " + cardType + " status =  " + status);

		if (status != null) {
			hqlFilter.addEQFilter("status", status);
		} else {
			hqlFilter.addSql(" where 1 = 1 ");
		}

		if (cardType != null) {
			hqlFilter
					.addSql(" and cardId in (select  id from com.hk.commons.entity.Card where type = '"
							+ cardType + "' )");
		}

		if (StringHelper.isNotEmpty(userName)) {
			String sqlFilter = " and userId in ( select id from com.hk.commons.entity.sys.SysUser where name = "
					+ userName + " )";
			hqlFilter.addSql(sqlFilter);
		}

		System.out.println("hqlFileter =  " + hqlFilter.getWhereAndOrderHql());
		List<UserCard> cardTotalList = userCardService.findByFilter(hqlFilter);

		List<UserCard> cardList = userCardService.findByFilter(hqlFilter,
				req.getCurPage(), req.getPageSize());
		if (cardList != null && cardList.size() > 0) {
			for (UserCard userCard : cardList) {
				UserCardRes cardRes = new UserCardRes();

				ReqToModelHelper.copyReqValueToModel(userCard, cardRes);
				Card card = cardService.findById(userCard.getCardId());

				// 添加卡券的信息
				if (card != null) {
					cardRes.setCardRate(card.getRate().toString());
					cardRes.setCardType(card.getType());
					cardRes.setCardTypeStr(CardsTypeEnum.getTypeStr(card
							.getType()));
					cardRes.setCardDesc(card.getCardDesc());
				}
				// 添加卡券的状态信息
				cardRes.setStatus(userCard.getStatus());
				cardRes.setStatusStr(UserCardsStatusEnum
						.getUserCardStatus(userCard.getStatus()));

				// 添加用户姓名
				cardRes.setUserName(userService.getNameById(userCard
						.getUserId()));

				cardResList.add(cardRes);
			}
		}

		resp.setSize(cardTotalList.size());
		resp.setResult(cardResList);
		resp.setResultCode(StatusCode.SUCCESS.key());

		return resp;
	}

	/**
	 * 获取加息券
	 * 
	 * @param userId
	 *            用户id, cardId 加息券id
	 * @return
	 */
	@RequestMapping(value = "/sendCardToEveryOne", method = RequestMethod.GET)
	@ResponseBody
	public ResponseBase<Integer> sendCardToEveryOne() {
		ResponseBase<Integer> resp = new ResponseBase<Integer>();
		try {
			// 01 判断参数配置是否存在，如果不能获取加息券id则直接退出
			Parameter parmCard = parmService
					.getByName(ConstantCard.SEND_CARD_ID);
			if (parmCard == null || StringHelper.isEmpty(parmCard.getValue01())) {
				resp.setSize(0);
				resp.setResult(0);
				resp.setResultCode(StatusCode.SUCCESS.key());

				logger.info("在参数表中找不到参数 SEND_CARD_ID， 或参数值为空");
				return resp;
			}

			Card card = null;
			Integer cardId = Integer.valueOf(parmCard.getValue01());

			card = cardService.findById(cardId);

			// 02 判断加息券是否存在，如果不存在则直接退出
			if (card == null) {
				resp.setSize(0);
				resp.setResult(0);
				resp.setResultCode(StatusCode.SUCCESS.key());

				logger.info("加息券不存在 cardId = " + cardId);
				return resp;
			} else {
				cardId = card.getId();
			}

			Integer sendSize = 0;
			HqlFilter hqlFilter = new HqlFilter();
			List<SysUser> userList = userService.findByFilter(hqlFilter);
			for (SysUser user : userList) {
				try {
					// 发放加息券
					UserCard userCard = new UserCard(user.getId(), cardId);
					// 01 给用添加卡券
					userCardService.add(userCard);

					// 02 更新卡券的已用数目，加1
					card.setUsedNum(card.getUsedNum() + 1);
					cardService.update(card);
					sendSize++;
				} catch (Exception e) {
					logger.info("sendCardToEveryOne get userCard error :"
							+ " userId = " + user.getId() + e.getMessage());
					continue;
				}
			}
			resp.setSize(sendSize);
			resp.setResult(sendSize);
			resp.setResultCode(StatusCode.SUCCESS.key());
		} catch (Exception e) {
			logger.info("send userCard has error :" + e.getMessage());
		}

		return resp;
	}

}
